<template>
  <div>
    <basic-container class="user">
      <div class="user__containter flex">
        <div class="user__tree">
          <avue-tree
            ref="tree"
            v-model="treeForm"
            :option="treeOption"
            :data="treeData"
            @node-click="nodeClick"
            @save="saveTree"
          >
            <span
              slot-scope="{ node, data }"
              class="custom-tree-node"
            >
              <span>{{ node.label }}</span>
              <el-dropdown :disabled="!data.id">
                <i class="el-icon-more"></i>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item>
                    <el-button
                      type="text"
                      icon="el-icon-edit"
                      @click="() => editClassify(data)"
                    >
                      编辑
                    </el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button
                      :disabled="data.id === '1'"
                      type="text"
                      icon="el-icon-delete"
                      @click="() => delClassify(data)"
                    >
                      删除
                    </el-button>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </span>
          </avue-tree>
        </div>
        <div class="user__main flex-1">
          <avue-crud
            ref="crud"
            v-model="form"
            :option="option"
            :page.sync="page"
            :search.sync="searchForm"
            :table-loading="tableLoading"
            :data="tableData"
            @search-change="searchChange"
            @search-reset="searchReset"
          >
            <template #recommendFlag="scope">
              <el-switch
                :value="scope.row.recommendFlag"
                inactive-value="0"
                active-value="1"
                @change="handleSwitchChange($event, scope.row)"
              />
            </template>
            <template #shieldFlag="scope">
              <el-switch
                :value="scope.row.shieldFlag"
                inactive-value="0"
                active-value="1"
                @change="handleShieldChange($event, scope.row)"
              />
            </template>
            <template #hotFlag="scope">
              <el-switch
                :value="scope.row.hotFlag"
                inactive-value="0"
                active-value="1"
                @change="handleHotChange($event, scope.row)"
              />
            </template>
            <template slot="menuLeft">
              <el-button
                class="filter-item"
                type="primary"
                size="small"
                icon="el-icon-plus"
                @click="addTopic"
              >
                新增话题
              </el-button>
            </template>
            <template
              slot="menu"
              slot-scope="scope"
            >
              <el-button
                type="text"
                size="small"
                @click="editTopic(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                type="text"
                size="small"
                @click="deletetopic(scope.row)"
              >
                删除
              </el-button>
              <el-dropdown
                ref="dropdown"
                trigger="click"
              >
                <el-button
                  type="text"
                  size="small"
                  style="margin-left: 5px"
                  @click="moveSelect(scope.row)"
                >
                  移动
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item
                    v-for="(item, index) in newData"
                    :key="index"
                    @click.native="movetopic(item, scope.row)"
                  >
                    {{ item.name }}
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <el-button
                type="text"
                size="small"
                @click="topic(scope.row)"
              >
                动态列表
              </el-button>
            </template>
          </avue-crud>
        </div>
      </div>
    </basic-container>
    <edit-classify
      :id="id"
      v-model="classifyVisible"
      :action="action"
      @success="init()"
    ></edit-classify>
    <add-topic
      :id="id"
      v-model="topicVisible"
      :action="action"
      :node-obj="nodeObj"
      :node-index="nodeIndex"
      @refresh="getList"
    ></add-topic>
    <!--话题管理-->
    <topic-manage-dialog
      v-if="manageVisible"
      v-model="manageVisible"
      :type="type"
      :topic-name="topicName"
    ></topic-manage-dialog>
  </div>
</template>
<script>
import {
  selectTopic,
  insertTopic,
  deleteTopic,
  selectTopicList,
  deleteTopicList,
  updateTopicList,
} from '@/api/core/topic';
// import { deptRoleList } from '@/api/admin/role';
import { tableOption, formOption } from '@/const/crud/community-content/topic';
import crudMixins from '@/mixins/crud';
import editClassify from './component/editClassify';
import addTopic from './component/addTopic';
import topicManageDialog from './component/topicManageDialog.vue';
import { SELECT_STATUS, SHEILD_STATUS, TOPIC_HOT_FLAG } from '@/const/type';
export default {
  name: 'SysUser',
  components: {
    editClassify,
    addTopic,
    topicManageDialog,
  },
  mixins: [crudMixins],
  data() {
    return {
      treeForm: {},
      SELECT_STATUS: SELECT_STATUS,
      SHEILD_STATUS: SHEILD_STATUS,
      TOPIC_HOT_FLAG,
      treeOption: {
        nodeKey: 'id',
        addBtn: true,
        menu: false,
        addBtnText: '提交',
        props: {
          label: 'name',
          value: 'id',
        },
        formOption: formOption(false),
      },
      treeData: [],
      option: tableOption(),
      role: [],
      form: {},
      baseId: '',
      excelUpload: false,
      classifyVisible: false,
      topicVisible: false,
      manageVisible: false,
      action: '',
      topicName: '',
      type: '',
      id: '',
      nodeObj: {},
      nodeIndex: '',
      newData: [],
    };
  },
  created() {
    this.init();
  },
  methods: {
    //移动 去掉当前分类
    moveSelect(row) {
      const arr = this.treeData.filter(
        (item) => ![row].some((ele) => ele.classifyId === item.id)
      );
      this.newData = arr;
    },
    //移动
    movetopic(item, row) {
      const params = {
        id: row.id,
        classifyId: item.id,
      };
      updateTopicList(params).then(() => {
        this.$message.success('移动成功');
        this.getList();
      });
    },
    handleShieldChange(e, row) {
      const tip = e === '1' ? '开启屏蔽' : '关闭屏蔽';
      const status = e === '1' ? SHEILD_STATUS.SHEILD : SHEILD_STATUS.NOSHEILD;
      this.$confirm(`是否${tip}状态`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        const params = {
          id: row.id,
          shieldFlag: status,
        };
        updateTopicList(params).then(() => {
          this.getList();
          this.$message.success(`${tip}`);
        });
      });
    },
    ///加hot
    handleHotChange(e, row) {
      const status = e === '1' ? TOPIC_HOT_FLAG.HOT : TOPIC_HOT_FLAG.NOHOT;
      if (status === TOPIC_HOT_FLAG.HOT) {
        this.$confirm(`是否给该话题加'hot'标识？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          this.submitHotData(status, row.id);
        });
      } else {
        this.submitHotData(status, row.id);
      }
    },

    submitHotData(status, id) {
      const params = {
        id: id,
        hotFlag: status,
      };
      updateTopicList(params).then(() => {
        this.getList();
      });
    },

    //开启推荐
    handleSwitchChange(e, row) {
      const tip = e === '1' ? '开启推荐' : '关闭推荐';
      const status =
        e === '1' ? SELECT_STATUS.SELECTED : SELECT_STATUS.NOSELECTED;
      this.$confirm(`是否${tip}状态`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        const params = {
          id: row.id,
          recommendFlag: status,
          // type: '1',
        };
        updateTopicList(params).then(() => {
          this.getList();
          this.$message.success(`${tip}`);
        });
      });
    },
    //新增分类
    saveTree(node, data, done) {
      console.log('data', data);
      insertTopic(data)
        .then(() => {
          this.init();
          this.$message.success('新增话题分类成功');
          done();
        })
        .catch(() => {
          done();
        });
    },
    //编辑分类
    editClassify(data) {
      this.id = data.id;
      this.classifyVisible = true;
      this.action = 'edit';
      console.log('daa', data);
    },
    //删除分类
    delClassify(data) {
      this.$confirm('确认删除该分类吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(function () {
          return deleteTopic(data.id);
        })
        .then(() => {
          this.init();
          this.$message.success('删除成功');
        });
    },
    //新增话题
    addTopic() {
      this.action = 'add';
      this.topicVisible = true;
    },
    //编辑话题
    editTopic(row) {
      this.action = 'edit';
      this.topicVisible = true;
      this.id = row.id;
    },
    //删除
    deletetopic(row) {
      this.$confirm('确认删除该话题吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(function () {
          return deleteTopicList(row.id);
        })
        .then(() => {
          this.init();
          this.$message.success('删除话题成功');
        });
    },
    //话题管理
    topic(row) {
      this.topicName = `#${row.name.trim()}#`;
      this.manageVisible = true;
      this.type = 'topic';
    },
    async init() {
      await selectTopic().then((response) => {
        this.treeData = response.data.data;
        this.treeData.unshift({ name: '全部', id: '' });
        this.nodeIndex = this.treeData[0].id;
        this.nodeObj.id = undefined;
        this.$nextTick(() => {
          this.$refs.tree.setCurrentKey(
            this.treeData[0][this.treeOption.nodeKey]
          );
        });
      });
      await this.getList();
    },
    //点击每行
    nodeClick(data) {
      this.nodeObj = data;
      this.getList();
    },
    getList() {
      this.tableLoading = true;
      console.log('this.nodeObj', this.nodeObj.id);
      const params = {
        classifyId: this.nodeObj.id ? this.nodeObj.id : this.nodeIndex,
      };
      const timeObj = {};
      if (this.searchForm.createTime && this.searchForm.createTime.length) {
        timeObj.createStartTime = this.searchForm.createTime[0];
        timeObj.createEndTime = this.searchForm.createTime[1];
        delete this.searchForm.createTime;
      }
      selectTopicList({ ...params, ...this.searchForm, ...timeObj })
        .then((res) => {
          this.tableData = res.data.data;
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
  },
};
</script>
<style lang="scss" scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.user {
  ::v-deep {
    .el-card__body {
      overflow: hidden;
    }
  }

  &__containter {
    height: 100%;
  }

  &__tree {
    width: 250px;
    padding-top: 3px;
    padding-right: 20px;
    box-sizing: border-box;
    height: 100%;
    flex-shrink: 0;
    ::v-deep {
      .el-tree-node__content {
        height: 40px;
      }
      .el-tree-node__label {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }

  &__main {
    overflow: auto;
    .el-card__body {
      padding-top: 0;
    }
  }
}
</style>
